from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.parsers import MultiPartParser
from rest_framework.permissions import AllowAny
import io
import fitz  # PyMuPDF 解析 PDF
import docx  # python-docx 解析 Word
import json
import csv

from .models import AnalysisChatSession, AnalysisChatMessage
from .serializers import AnalysisChatSessionSerializer
from user.models import SysUser


class FileParseView(APIView):
    """文件解析视图 - 仅支持TXT文件"""
    parser_classes = [MultiPartParser]
    permission_classes = [AllowAny]  # 允许任何用户访问
    MAX_FILE_SIZE = 10 * 1024 * 1024  # 10MB

    def post(self, request):
        """解析上传的TXT文件"""
        try:
            # 获取文件
            file_obj = request.FILES.get('file')
            if not file_obj:
                return Response(
                    {"detail": "未找到上传的文件"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 验证文件大小
            if file_obj.size > self.MAX_FILE_SIZE:
                return Response(
                    {"detail": f"文件过大（{file_obj.size/1024/1024:.2f}MB），最大支持10MB"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 获取文件扩展名
            file_name = file_obj.name
            file_ext = file_name.split('.')[-1].lower() if '.' in file_name else ''
            
            # 仅支持TXT文件
            if file_ext != 'txt':
                return Response(
                    {"detail": f"不支持的文件格式（{file_ext}），仅支持TXT文件"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 解析TXT文件内容
            try:
                file_content = file_obj.read().decode('utf-8')
                
                # 验证解析结果
                if not file_content.strip():
                    return Response(
                        {"detail": "文件解析成功，但未提取到有效内容（文件为空）"},
                        status=status.HTTP_400_BAD_REQUEST
                    )
                
                return Response({
                    "content": file_content,
                    "filename": file_name,
                    "file_type": file_ext
                }, status=status.HTTP_200_OK)
                
            except UnicodeDecodeError:
                return Response(
                    {"detail": "文件编码错误，请确保TXT文件使用UTF-8编码"},
                    status=status.HTTP_400_BAD_REQUEST
                )
            except Exception as parse_error:
                return Response(
                    {"detail": f"文件解析失败：{str(parse_error)}"},
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
                
        except Exception as e:
            return Response(
                {"detail": f"处理请求失败：{str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


class AnalysisChatHistoryView(APIView):
    """获取用户的企业战略分析会话历史记录"""
    permission_classes = [AllowAny]  # 允许任何用户访问

    def get(self, request):
        # 获取用户ID（实际项目中建议从认证系统获取）
        user_id = request.query_params.get('user_id')
        if not user_id:
            return Response(
                {"detail": "缺少user_id参数"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 查询用户的所有会话（按更新时间倒序）
        try:
            user = SysUser.objects.get(id=user_id)
            sessions = AnalysisChatSession.objects.filter(user=user).order_by('-updated_at')

            # 序列化并返回数据
            serializer = AnalysisChatSessionSerializer(sessions, many=True)
            return Response(serializer.data)

        except SysUser.DoesNotExist:
            return Response(
                {"detail": "用户不存在"},
                status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            return Response(
                {"detail": f"获取历史记录失败：{str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def post(self, request):
        """保存新的对话会话"""
        try:
            user_id = request.data.get('user_id')
            title = request.data.get('title', '未命名分析')
            messages = request.data.get('messages', [])

            if not user_id:
                return Response(
                    {"detail": "缺少user_id参数"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 获取用户
            user = SysUser.objects.get(id=user_id)

            # 创建会话
            session = AnalysisChatSession.objects.create(
                user=user,
                title=title
            )

            # 保存消息
            for msg_data in messages:
                AnalysisChatMessage.objects.create(
                    session=session,
                    sender=msg_data.get('sender', 'user'),
                    content=msg_data.get('content', ''),
                    tokens_used=msg_data.get('tokens_used', 0),
                    response_time=msg_data.get('response_time', 0.0)
                )

            # 返回创建的会话
            serializer = AnalysisChatSessionSerializer(session)
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        except SysUser.DoesNotExist:
            return Response(
                {"detail": "用户不存在"},
                status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            return Response(
                {"detail": f"保存会话失败：{str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def delete(self, request):
        """删除指定的会话"""
        try:
            session_id = request.query_params.get('session_id')
            user_id = request.query_params.get('user_id')

            if not session_id or not user_id:
                return Response(
                    {"detail": "缺少session_id或user_id参数"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 验证用户权限并删除会话
            user = SysUser.objects.get(id=user_id)
            session = AnalysisChatSession.objects.get(id=session_id, user=user)
            session.delete()

            return Response({"detail": "会话删除成功"}, status=status.HTTP_200_OK)

        except SysUser.DoesNotExist:
            return Response(
                {"detail": "用户不存在"},
                status=status.HTTP_404_NOT_FOUND
            )
        except AnalysisChatSession.DoesNotExist:
            return Response(
                {"detail": "会话不存在或无权限"},
                status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            return Response(
                {"detail": f"删除会话失败：{str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )